package cn.hm.security;

import cn.hm.entity.User;
import cn.hm.mapper.PermissionMapper;
import cn.hm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 认证流程
 * spirng security 接入数据库实现认证
 * @author Mxb
 * @version 1.0
 * @date 2020/7/28 9:18
 */
@Service
public class UserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);

        // 从数据库查询用户信息
        User user = userMapper.loadUserByUsername(s);
        if(user == null){
            // 如果用户查不到，返回null，由provider来抛异常
            return null;
        }
        // 根据用户id 查询权限
        List<String> permissions = permissionMapper.selectPermissionByUserId(user.getId());
        String[] array = new String[permissions.size()];
        // 将集合 转为数组
        permissions.toArray(array);

        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.getFullname()).password(user.getPassword()).authorities(array).build();
        return userDetails;
    }
}
